package com.example.handler;

import cn.dev33.satoken.stp.StpUtil;
import com.example.mapper.FraudEvidenceMapper;
import com.example.mapper.UserMapper;
import com.example.model.FraudRiskResult;
import com.example.model.Result;
import com.example.model.pojo.FraudEvidence;
import com.example.model.pojo.Person;
import com.example.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 高风险处理器
 * 处理评分大于等于70的高风险案例
 * 
 * @author system
 */
@Component
@Order(1)
@RequiredArgsConstructor
@Slf4j
public class HighRiskHandler implements RiskHandler {

  private final UserService userService;
  private final UserMapper userMapper;
  private final FraudEvidenceMapper fraudEvidenceMapper;

  @Override
  public boolean canHandle(FraudRiskResult result) {
    return result.getRiskLevel() == 2; // 高风险
  }

  @Override
  public void handle(FraudRiskResult result) {
    if (!canHandle(result)) {
      return;
    }

    log.info("处理高风险案例，用户地址：{}，风险评分：{}", result.getUserAddress(), result.getScore());

    // 1. 冻结账户，永久封禁
    StpUtil.disable(result.getUserProfile().getId(), -1);
    userService.banUser(result.getUserProfile().getId(), null, 2);

    // 2. 记录风险证据到数据库
    FraudEvidence evidence = FraudEvidence.builder()
        .userAddress(result.getUserAddress())
        .evidenceType("高风险欺诈行为")
        .evidenceContent(result.getEvidenceSummary())
        .riskScore(result.getScore())
        .handlerId(StpUtil.getLoginIdAsLong())
        .handleTime(result.getDetectionTime())
        .status(0)
        .build();
    fraudEvidenceMapper.insert(evidence);

    // 3. 通知管理员进行人工审核
    log.warn("发现高风险欺诈行为，已冻结账户并通知管理员，用户地址：{}", result.getUserAddress());
  }

  @Override
  public int getOrder() {
    return 1; // 高风险优先处理
  }
}